"""药品信息上传任务

处理药品信息到SaaS平台的定时上传。
使用分批处理机制，提高大数据量处理的稳定性和效率。
"""

import logging
from config.config_manager import get_hospital_config
from service.upload_drug_info_service import drug_upload_service

# 日志
logger = logging.getLogger(__name__)


def upload_drug_info_job():
    """药品信息上传任务 - 使用service层"""
    hospital_name = drug_upload_service.hospital_name
    
    try:
        logger.info(f"[{hospital_name}] 开始执行药品信息定时上传任务")
        
        # 1. 获取药品信息总数
        total_count = drug_upload_service.get_drug_count()
        if total_count == 0:
            logger.warning("未获取到药品数据，跳过上传")
            return
        
        logger.info(f"从{hospital_name} HIS 系统获取到 {total_count} 条药品数据")
        
        # 2. 使用药品上传服务进行分批上传
        upload_result = drug_upload_service.upload_drugs_in_batches()
        
        # 3. 处理上传结果
        if upload_result["total_uploaded"] > 0:
            logger.info(f"分批上传完成: 成功 {upload_result['success_batches']}/{upload_result['total_batches']} 批")
            logger.info(f"数据统计: 成功上传 {upload_result['total_uploaded']} 条，失败 {upload_result['total_failed']} 条")
        else:
            logger.error("分批上传失败，没有数据成功上传")

        logger.info("药品信息上传任务执行完成")
        
    except Exception as e:
        logger.error(f"药品信息上传任务执行失败: {e}", exc_info=True)
        raise
